package com.yuan.aiswshop.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.common.utils.PageUtils;
import com.yuan.common.utils.Query;

import com.yuan.aiswshop.product.dao.CategoryDao;
import com.yuan.aiswshop.product.entity.CategoryEntity;
import com.yuan.aiswshop.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> list = this.baseMapper.selectList(null);
        List<CategoryEntity> level1Menus = list.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid()==0)
                .peek(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, list));
                })
                .sorted((categoryEntity1, categoryEntity2)->{
                    return categoryEntity1.getSort() - categoryEntity2.getSort();
                })
                .collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeCategoryByIds(List<Long> asList) {
        // TODO 处理删除
        this.baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> list) {
        return list.stream()
                .filter(category ->categoryEntity.getCatId().equals(category.getParentCid()))
                .peek(category -> {
                    category.setChildren(getChildrens(category, list));
                })
                .sorted((categoryEntity1, categoryEntity2)->{
                    return categoryEntity1.getSort() - categoryEntity2.getSort();
                })
                .collect(Collectors.toList());
    }

}